<template>
  <div class="notice-container">
    <!-- 管理员发布公告区域 -->
    <div class="publish-area" v-if="isAdmin">
      <el-card class="publish-card">
        <template #header>
          <div class="card-header">
            <span>发布新公告</span>
          </div>
        </template>
        <el-form :model="noticeForm" label-width="80px">
          <el-form-item label="标题">
            <el-input v-model="noticeForm.title" placeholder="请输入公告标题"/>
          </el-form-item>
          <el-form-item label="内容">
            <el-input
              v-model="noticeForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入公告内容"
            />
          </el-form-item>
          <el-form-item label="公告类型">
            <el-radio-group v-model="noticeForm.type" default-first-option>
              <el-radio :label="1" checked>普通公告</el-radio>
              <el-radio :label="2">重要公告</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="publishNotice">发布公告</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 公告列表展示区域 -->
    <div class="notice-list" v-if="notices.length > 0">
      <el-timeline>
        <el-timeline-item
          v-for="notice in notices"
          :key="notice.id"
          :timestamp="notice.createTime"
          placement="top"
          :type="notice.type"
        >
          <el-card>
            <template #header>
              <div class="notice-header">
                <h3>{{ notice.title }}</h3>
                <el-tag :type="notice.type === '普通公告' ? 'success' : 'warning'">
                  {{ notice.type }}
                </el-tag>
              </div>
            </template>
            <p class="notice-content">{{ notice.content }}</p>
            <div class="notice-footer">
              <span>发布人: {{ notice.nickName }}</span>
              <el-button 
                v-if="isAdmin" 
                type="danger" 
                size="small"
                @click="deleteNotice(notice.id)"
              >删除</el-button>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </div>
    <div class="notice-list" v-if="notices.length <= 0">
      <el-empty description="暂无任何公告" />
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  setup() {
    const isAdmin = ref(true) // 是否是管理员
    const noticeForm = reactive({
      title: '',
      content: '',
      type: 1,
      userId: ''
    })

    // 模拟公告数据
    const notices = ref([
      {
        id: 1,
        title: '新功能上线通知',
        content: '景区预约功能已正式上线，欢迎大家使用体验！',
        createTime: '2024-01-27 15:30',
        nickName: '系统管理员',
        type: '普通公告'
      }
    ])

    const checkLogin = () => {
      const user = JSON.parse(sessionStorage.getItem('userInfo'))
      if(user === null || user === undefined || user === '') {
        ElMessage.error('请先登录')
        return ''
      }
      return user
    }

    // 发布公告
    const publishNotice = () => {
      const user = checkLogin()
      if(user === '') {
        return
      }

      if (!noticeForm.title.trim() || !noticeForm.content.trim()) {
        ElMessage.warning('标题和内容不能为空')
        return
      }
      
      noticeForm.userId = user.id
      axios.post('/api/notice',noticeForm)
      .then(res => {
        if(res.data.code === 200){
          const newNotice = res.data.data
          notices.value.unshift(newNotice)
          noticeForm.title = ''
          noticeForm.content = '' 
          ElMessage({
            message: "发布成功",
            type: 'success',
          })
        }else{
          ElMessage({
            message: res.data.message,
            type: 'error',
          })
        }
      })
      .catch(err => {
        ElMessage({
          message: "发布失败",
          type: 'error',
        })
      })
    }

    // 删除公告
    const deleteNotice = (id) => {
      ElMessageBox.confirm('确认要删除该公告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete('/api/notice/' + id)
          .then(res => {
            if(res.data.code === 200) {
              notices.value = notices.value.filter(notice => notice.id !== id)
              ElMessage.success('删除成功')
            } else {
              ElMessage.error(res.data.message)
            }
          })
          .catch(() => {
            ElMessage.error('删除失败')
          })
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }

    onMounted(() => {
      // 这里应该调用接口判断当前用户是否是管理员
      // isAdmin.value = localStorage.getItem('userRole') === 'admin'
      //加载所有系统公告
      getAllNotice()
    })

    const getAllNotice = () => {
      axios.get('/api/notice')
      .then(res => {
        if(res.data.code === 200){
          notices.value = res.data.data
          ElMessage({
            message: "加载成功",
            type: 'success',
          })
        }else{
          ElMessage({
            message: res.data.message,
            type: 'error',
          })
        }
      })
      .catch(err => {
        ElMessage({
          message: "获取数据失败",
          type: 'error',
        })
      })
    }

    return {
      isAdmin,
      noticeForm,
      notices,
      publishNotice,
      deleteNotice,
      getAllNotice,
      checkLogin
    }
  }
}
</script>

<style scoped>
.notice-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.publish-area {
  margin-bottom: 30px;
}

.notice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notice-header h3 {
  margin: 0;
}

.notice-content {
  line-height: 1.6;
  margin: 10px 0;
}

.notice-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.el-timeline {
  margin-top: 20px;
}

.el-card {
  margin-bottom: 10px;
}
</style>